import { Plugin } from '@nuxt/types';
import qs from 'qs';

const pointURL = 'http://d.pezy.cn/data/report/h5';

declare module '@nuxt/types' {
    interface Context {
        $point: any;
    }
}

declare module 'vue/types/vue' {
    interface Vue {
        $point: any;
    }
}

declare module 'vuex/types/index' {
    interface Store<S> {
        $point: any
    }
}


function param() {
    const inBrowser: any = typeof window !== 'undefined';
    const UA: any = inBrowser && window.navigator.userAgent.toLowerCase();
    const os = /iPhone|iPad|iPod/i.test(UA) ? 'ios' : 'android';
    let appVersion: any = '';
    let app: any = '';

        //ie
    if (UA.indexOf('msie') >= 0) {
        appVersion = UA.match(/msie ([\d.]+)/)[1];
        app = 'IE';
    }
    //firefox
    else if (UA.indexOf('firefox') >= 0) {
        appVersion = UA.match(/firefox\/([\d.]+)/)[1];
        app = 'Firefox';
    }
    //Chrome
    else if (UA.indexOf('chrome') >= 0) {
        appVersion = UA.match(/chrome\/([\d.]+)/)[1];
        app = 'Chrome';
    }
    //Opera
    else if (UA.indexOf('opera') >= 0) {
        appVersion = UA.match(/opera.([\d.]+)/)[1];
        app = 'Opera';
    }
    //Safari
    else if (UA.indexOf('Safari') >= 0) {
        appVersion = UA.match(/version\/([\d.]+)/)[1];
        app = 'Safari';
    }

    let point = {
        verCode: '1.0.0',
        devVendor: 'h5',
        app,
        appVersion: appVersion ? appVersion : '',
        screen: `${window.screen.width}x${window.screen.height}`,
        os,
        osVersion: '',
        ua: UA,
        url: encodeURIComponent(location.href),
    };

    return point;
}

const myPlugin: Plugin = ({context, $axios}: any, inject) => {
    //adType // 0-曝光, // 1-点击 // 2-关闭
    inject('point', (options: any, adType: any = 0) => {
        let point = param();
        point = Object.assign(point, {
            ts: new Date().valueOf(),
            type: 'h5_ad',
            adType, 
        }, options);

        $axios.post(`${pointURL}`, point)
        .then((res: any) =>{})
        .catch((err: any) => {})
    })
}

export default myPlugin;